const restify = require('restify');
const corsMiddleware = require('restify-cors-middleware');
const config = require('config');
const validator = require('./libs/validator');
const _events = ['list', 'retrieve', 'putCollection', 'update', 'create', 'post', 'deleteCollection', 'delete'];
const session = require('restify-session')({
    sidHeader: 'authorization',
    connection: config.dbConfig.redis
});
const cors = corsMiddleware({
  preflightMaxAge: 5, //Optional
  origins: ['*'],
  allowHeaders: ['authorization']
})


exports.init = (server) => {
    server.use(session.sessionManager);
    server.use(restify.plugins.dateParser());
    server.use(restify.plugins.queryParser({mapParams:true}));
    server.use(restify.plugins.gzipResponse());
    server.use(restify.plugins.bodyParser({ mapParams: true }));
    server.pre(cors.preflight);
    server.use(cors.actual);

    server.get('/apidemo/api/:resources', send);
    server.get('/apidemo/api/:resources/:id', send);
    server.post('/apidemo/api/:resources', send);
    server.post('/apidemo/api/:resources/:id', send);
    server.put('/apidemo/api/:resources', send);
    server.put('/apidemo/api/:resources/:id', send);
    server.del('/apidemo/api/:resources', send);
    server.del('/apidemo/api/:resources/:id', send);

    server.get('/apidemo/api/version', (req, res, next) => {
        respond(res, { version: config.version });
    });
}

function send(req, res, next) {
    // console.log(req.params);
    // console.log(req.session);

    if(config.appDebug){
        req.session={
            id:"1",
            sid:"aaaa"
        };
    }
    if ((!req.session || !req.session.id) && req.params.resources != 'login') {
        gotoLogin(res);
    } else {
        var resources = req.params.resources;
        if (resources) {
            var method = req.method.toUpperCase();
            var event = emitEvent(method, req.params.id);
            if (supportEvent(event, req)) {
                return invoke(req, event, (result) => {
                    respond(req, res, result);
                });
            } else {
                var errorstr = 'No supported event found!';
                return errorstr;
            }
        } else {
            return 'No supported resources found!';
        }
    }
    return next();
}

function invoke(req, event, callback) {
    var method = req.method.toUpperCase();
    var checkedresult = true;
    if (method == 'PUT' || method == 'POST') {
        var valiconf = loadModule('./validate/' + req.params[0] + '.json');
        if (valiconf) {
            var result = validator.validate(req.params, valiconf);
            if (result) {
                checkedresult = false;
                callback({
                    error: result
                });
            }
        }
    }
    if (checkedresult) {
        //加载对应的资源处理Module
        var module = loadModule('./api/' + req.params.resources);
        if (module) {
            var service = new module.service();
            var fn = service[event];
            var id = req.params.id;
            delete req.params.resources;
            delete req.params.id;
            req.params['*session'] = req.session;
            if (id) {
                fn(id, req.params, function(result) {
                    callback(result);
                });
            } else {
                fn(req.params, function(result) {
                    callback(result);
                });
            }
        } else {
            var errorstr = 'No module found!';
            return errorstr;
        }
    }

}

function emitEvent(method, id) {
    var localEvent;
    switch (method) {
        case 'GET': //查询（有无id的判断）
            localEvent = id ? 'retrieve' : 'list';
            break;
        case 'PUT': //修改
            localEvent = id ? 'update' : 'putCollection';
            break;
        case 'POST': //增加
            localEvent = id ? 'post' : 'create';
            break;
        case 'DELETE': //删除
            localEvent = id ? 'delete' : 'deleteCollection';
            break;
    }
    return localEvent;
}

function supportEvent(event, req) {
    var result = false;
    _events.forEach(function(_event) {
        if (event === _event) {
            result = true;
        }
    });
    return result;
}

function respond(req, res, result) {
    var stringfyResult = JSON.stringify(result);
    res.setHeader("Content-Type", "text/json;charset=UTF-8");
    res.setHeader("authorization", req.session.sid);
    res.end(stringfyResult);
}

function gotoLogin(res) {
    res.setHeader("Content-Type", "text/json;charset=UTF-8");
    res.status(401);
    //跳转到登录页面
    // res.redirect(401, 'www.foo.com/login', next);
    res.end();
}

function loadModule(path) {
    try {
        return require(path);
    } catch (err) {
        return null;
    }
}